<template>
  <div class="container clearfix">
    <div class="filter">
      <h2 class="title">
        筛选查询
      </h2>
      <div class="section">
        <span class="tip">
          订单号
        </span>
        <div class="content">
          <el-input v-model="search_form.orderId" placeholder="请输入订单号" />
        </div>
      </div>
      <div class="section">
        <span class="tip">
          项目名称
        </span>
        <div class="content">
          <el-input v-model="search_form.projectName" placeholder="请输入项目名称" />
        </div>
      </div>
<!--      <div class="section">-->
<!--        <span class="tip">-->
<!--          分类-->
<!--        </span>-->
<!--        <el-select v-model="search_form.projectCategoryId" placeholder="请选择">-->
<!--          <el-option v-for="item in class_arr" :key="item.value" :label="item.label" :value="item.value" />-->
<!--        </el-select>-->
<!--      </div>-->
      <div class="section">
        <span class="tip">
          医院名称
        </span>
        <div class="content">
          <el-input v-model="search_form.hospitalName" placeholder="请输入内容" />
        </div>
      </div>
      <div class="section">
        <span class="tip">
          是否升单
        </span>
        <el-select v-model="search_form.whetherUpgrade" placeholder="请选择">
          <el-option v-for="item in whetherUpgrade_arr" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </div>
      <div class="section">
        <span class="tip">
          用户姓名
        </span>
        <div class="content">
          <el-input v-model="search_form.userInfo" placeholder="请输入用户姓名或者手机号" />
        </div>
      </div>
      <div class="section">
        <span class="tip">
          用户类型
        </span>
        <el-select v-model="search_form.userType" placeholder="请选择">
          <el-option v-for="item in user_arr" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </div>
      <div class="section">
        <span class="tip">
          购买类型
        </span>
        <el-select v-model="search_form.buyType" placeholder="请选择">
          <el-option v-for="item in buy_arr" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </div>
      <div class="section">
        <span class="tip">
          订单状态
        </span>
        <el-select v-model="search_form.orderStatus" placeholder="请选择">
          <el-option v-for="item in order_status_arr" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </div>
      <div class="section">
        <span class="tip">
          付款类型
        </span>
        <el-select v-model="search_form.payProgress" placeholder="请选择">
          <el-option v-for="item in pay_progress_arr" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </div>
      <div class="btn-bar">
        <el-button type="primary" plain icon="el-icon-search" @click="search()">查询</el-button>
        <el-button type="primary" plain icon="el-icon-export" :loading="downloadLoading" @click="handleDownload()">导出</el-button>
        <el-button type="primary" plain class="el-icon-refresh" @click="reset()">重置</el-button>
      </div>
    </div>
    <div class="data-table">
      <el-table v-loading="table_loading" :data="tableData" border height="660" align="center" style="width: 100%">
        <el-table-column prop="orderId" align="center" label="订单号" />
        <el-table-column prop="projectName" align="center" label="项目名称" />
        <el-table-column prop="hospitalName" align="center" label="医院名称" />
        <el-table-column prop="userName" align="center" label="用户姓名" />
        <el-table-column prop="userType" align="center" label="用户类型" />
        <el-table-column prop="userPhone" align="center" width="110" label="手机号" />
        <el-table-column prop="buyType" align="center" label="购买类型" />
        <el-table-column prop="orderCreateDate" align="center" label="订单生成时间" />
        <el-table-column prop="payAmount" align="center" label="支付金额" />
        <el-table-column prop="payProgress" :formatter="payProgressForm" align="center" label="付款类型" />
        <el-table-column prop="orderStatusValue" align="center" label="订单状态" />
        <el-table-column prop="verificationCode" align="center" label="核销码" />
        <el-table-column prop="whetherUpgrade" align="center" label="是否升单" />
        <el-table-column prop="upgradeAmount" align="center" label="升单金额" />
        <el-table-column :formatter="typeFormat" align="center" label="奖励券" />
        <el-table-column prop="coupons" align="center" label="立减券" />
        <el-table-column fixed="right" label="操作" align="center" width="190">
          <template slot-scope="scope">
            <el-button type="success" size="small" @click="search_detail(scope.row)">查看</el-button>
            <el-button v-if="scope.row.orderStatus===4" type="primary" size="small" @click="refund(scope.row)">退款</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页器 -->
    <div class="block">
      <el-pagination
        background
        :page-size="pageSize"
        :page-sizes="[10,20,50,100]"
        :pager-count="11"
        layout="total, sizes, prev, pager, next"
        :total="total"
        @current-change="change_page"
        @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>
<script>
import { getCateDownList, getCateList } from '@/api/category'
import { exportGroupOrderFile } from '@/api/file'
import { getOrderList, orderRefund } from '@/api/order'
import { appType } from '@/utils/constanst'
export default {
  data() {
    return {
      value: true,
      table_loading: false,
      class_arr: [
      ],
      user_arr: [
        {
          value: '1',
          label: '会员'
        }, {
          value: '0',
          label: '普通'
        }
      ],
      buy_arr: [
        {
          value: '1',
          label: '团购'
        }, {
          value: '2',
          label: '单买'
        }
      ],
      whetherUpgrade_arr: [
        {
          value: 1,
          label: '是'
        }, {
          value: 0,
          label: '否'
        }
      ],
      order_status_arr: [
        {
          value: 0,
          label: '待使用'
        },
        {
          value: 1,
          label: '预约中'
        },
        {
          value: 2,
          label: '预约关闭'
        },
        {
          value: 3,
          label: '已核销'
        },
        {
          value: 4,
          label: '退款中'
        },
        {
          value: 5,
          label: '已退款'
        },
        {
          value: 6,
          label: '已付尾款'
        }

      ],
      pay_progress_arr:[
        {
          value: 0,
          label: '未支付'
        },
        {
          value: 1,
          label: '已付定金'
        },
        {
          value: 2,
          label: '已付全款'
        }
      ],
      total: 1,
      tableData: [],
      page: 1,
      pageSize: 10,
      search_form: {
        orderId: null, // 订单号
        projectName: '', // 项目名称
        projectCategoryId: null, // 项目分类
        hospitalName: '', // 医院名称
        whetherUpgrade: null,// 是否升单
        userInfo: '',//用户姓名
        userType: null,//用户类型
        buyType: null,//购买类型
        orderStatus: null,//订单状态
        payProgress:null,//付款类型
      },
      downloadLoading: false,
      filename: '订单列表'+new Date().getTime()  ,
      autoWidth: true,
      bookType: 'xlsx',
      model: 0// 0 初次加载   1表示条件筛选
    }
  },
  //新加路由保存参数
  beforeRouteLeave(to, from, next) {
    // const answer = window.confirm("当前页面搜索条件将会被保存");
    //更新 put
    let keyname = this.$route.name;
    let value = JSON.stringify(this.search_form);
    sessionStorage.setItem(keyname, value);
    next();
  },
  mounted() {
    if (sessionStorage.getItem(this.$route.name)) {
      this.search_form = JSON.parse(sessionStorage.getItem(this.$route.name));
    }
    this.search()
    this.get_cate_list()
  },
  methods: {
   payProgressForm(row){
     if (row.payProgress == 0) {
       return '未支付'
     }
     if (row.payProgress == 1) {
       return '已付定金'
     }
     if (row.payProgress == 2) {
       return '已付全款'
     }
    },
    //数据处理-奖励券
    typeFormat(row) {
      if (row.subsidiesStatus === 'null') {
        return null
      } else {
        if (row.subsidiesStatus === '1') {
          return row.subsidies + '/' + '待预约'
        }
        if (row.subsidiesStatus === '2') {
          return row.subsidies + '/' + '待消费'
        }
        if (row.subsidiesStatus === '3') {
          return row.subsidies + '/' + '待完成'
        }
        if (row.subsidiesStatus === '4') {
          return row.subsidies + '/' + '待领取'
        }
        if (row.subsidiesStatus === '5') {
          return row.subsidies + '/' + '已领取'
        }
        if (row.subsidiesStatus === '0') {
          return row.subsidies + '/' + '未知'
        }
        if (row.subsidiesStatus === '11') {
          return row.subsidies + '/' + '已失效'
        }
      }
    },
    // 筛选
    search() {
      this.model = 1
      this.get_list({
        'pageNum': this.page,
        'pageSize': this.pageSize,
        'orderId': this.search_form.orderId ? parseInt(this.search_form.orderId) : null,
        'projectName': this.search_form.projectName,
        // 'projectCategoryId': this.search_form.projectCategoryId ? parseInt(this.search_form.projectCategoryId) : null,
        'hospitalName': this.search_form.hospitalName,
        'whetherUpgrade': this.search_form.whetherUpgrade,
        'userInfo': this.search_form.userInfo,
        'userType': this.search_form.userType ,
        'buyType': this.search_form.buyType ? parseInt(this.search_form.buyType) : null,
        'payProgress': this.search_form.payProgress ,
        'orderStatus': this.search_form.orderStatus
      })
    },
    // 重置
    reset() {
      this.page = 1
      this.pageSize = 10
      this.search_form.orderId = ''
      this.search_form.hospitalName = ''
      // this.search_form.projectCategoryId = ''
      this.search_form.projectName = ''
      this.search_form.userInfo = ''
      this.search_form.userType = null
      this.search_form.buyType = null
      this.search_form.orderStatus = null
      this.search_form.payProgress = null
      this.search_form.whetherUpgrade = null
      this.get_list()
    },
    // 获取列表
    get_list(options = {
      'pageNum': this.page,
      'pageSize': this.pageSize
    }) {
      this.table_loading = true
      getOrderList(options).then((result) => {
        const res = result.data
        if (res.code === 0) {
          res.data.list.forEach(item => {
            if (item.userType === 0) {
              item.userType = '普通'
            } else if (item.userType === 1) {
              item.userType = '会员'
            }
            if (item.buyType === '1') {
              item.buyType = '团购'
              item.orderCreateDate = item.groupFinishDate
            } else if (item.buyType === '2') {
              item.buyType = '单买'
              item.orderCreateDate = item.orderCreateDate
            }
            if (item.whetherUpgrade === 0) {
              item.whetherUpgrade = '否'
            } else if (item.whetherUpgrade === 1) {
              item.whetherUpgrade = '是'
            }
          })
          this.tableData = res.data.list
          this.total = res.data.count
          this.table_loading = false
        }
      }).catch((err) => {
        this.table_loading = false
        //   this.$message.error('服务器网络错误，请稍后重试');
        this.$message.error(err)
      })
    },
    // 退款
    refund(row) {
      this.$confirm('确认退款？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        orderRefund({
          id: row.orderId + ''
        }).then((result) => {
          const res = result.data
          if (res.code === 0) {
            this.$message({
              type: 'success',
              message: '退款成功!'
            })
            this.search()
          } else {
            this.$message.error(res.msg)
          }
        }).catch((err) => {
          this.$message.error('服务器网络错误，请稍后重试')
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 查看详情
    search_detail(row) {
      this.$router.push({
        path: '/order_detail',
        query: {
          id: row.orderId,
          subsidies: row.subsidies,
          subsidiesStatus: row.subsidiesStatus
        }
      })
    },
    //表格导出
    handleDownload(options = {
      'pageNum': this.page,
      'pageSize': 100000000,
      'orderId': this.search_form.orderId ? parseInt(this.search_form.orderId) : null,
      'projectName': this.search_form.projectName,
      // 'projectCategoryId': this.search_form.projectCategoryId ? parseInt(this.search_form.projectCategoryId) : null,
      'hospitalName': this.search_form.hospitalName,
      'whetherUpgrade': this.search_form.whetherUpgrade,
      'userInfo': this.search_form.userInfo,
      'userType': this.search_form.userType ,
      'buyType': this.search_form.buyType ? parseInt(this.search_form.buyType) : null,
      'orderStatus': this.search_form.orderStatus
    }) {
      this.downloadLoading = true
      this.table_loading = true
      getOrderList(options).then((result) => {
        const res = result.data
        if (res.code === 0) {
          this.table_loading = false
          import('../../components/ExportExcel').then(excel => {
            const tHeader = ['订单号', '项目名称', '医院名称', '用户名称', '用户类型', '手机号', '购买类型', '订单生成时间', '支付金额',"付款类型", '订单状态', '核销码', '是否升单', '升单金额', '奖励券']
            const filterVal = ['orderId', 'projectName', 'hospitalName', 'userName', 'userType', 'userPhone', 'buyType', 'orderCreateDate', 'payAmount','payProgress', 'orderStatusValue', 'verificationCode', 'whetherUpgrade', 'upgradeAmount', 'subsidies']
            const list = res.data.list
            const data = this.formatJson(filterVal, list)
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: this.filename,
              autoWidth: this.autoWidth,
              bookType: this.bookType
            })
            this.downloadLoading = false
          })
        }
      }).catch((err) => {
        this.table_loading = false
        //   this.$message.error('服务器网络错误，请稍后重试');
        this.$message.error(err)
      })
    },
    //表格导出 --数据处理
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'subsidies') {
          return this.typeFormat(v)
        } else
        if (j === 'whetherUpgrade') {
          return v[j] === 0 ? '否' : '是'
        } else
        if (j === 'payProgress') {
          return this.payProgressForm(v)
        } else
        if (j === 'buyType') {
          return v[j] === '1' ? '团购' : '单买'
        } else
        if (j === 'userType') {
          return v[j] === 0 ? '普通' : '会员'
        } else {
          return v[j]
        }
      }))
    },
    // 导出 ---启用
    exports(options = {
      'pageNum': 1,
      'pageSize': this.pageSize,
      'orderId': this.search_form.orderId ? parseInt(this.search_form.orderId) : null,
      'projectName': this.search_form.projectName,
      // 'projectCategoryId': this.search_form.projectCategoryId ? parseInt(this.search_form.projectCategoryId) : null,
      'hospitalName': this.search_form.hospitalName,
      'whetherUpgrade': this.search_form.whetherUpgrade,
      'userInfo': this.search_form.userInfo,
      'userType': this.search_form.userType ,
      'buyType': this.search_form.buyType ? parseInt(this.search_form.buyType) : null,
      'payProgress': this.search_form.payProgress ,
      'orderStatus': this.search_form.orderStatus
    }) {
      // 调用生成导出文件接口
      var time = new Date().getTime()
      var fileName = time + '.xlsx'
      exportGroupOrderFile(options, { responseType: 'arraybuffer' }).then((result) => {
        // 调用下载导出文件接口
        if (result.status === 200) {
          const blob = new Blob([result.data], { type: 'application/x-xlsx' })
          // let fileName = result.headers['content-disposition'].match(/fushun(\S*)xlsx/)[0]
          if (window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(blob, fileName)
          } else {
            var link = document.createElement('a')
            link.href = window.URL.createObjectURL(blob)
            link.download = fileName
            link.click()
            window.URL.revokeObjectURL(link.href)
          }
        } else {
          this.$message.error('导出失败！')
        }
      })
    },
    // 获取分类列表
    get_cate_list() {
      getCateDownList({
        'pageNum': 1,
        'pageSize': 1000
      }).then((result) => {
        const res = result.data
        if (res.code === 0) {
          const arr = []
          res.data.list.forEach(item => {
            arr.push({
              value: item.id,
              label: item.categoryName
            })
          })
          this.class_arr = arr
        } else {
          this.$message.error(res.msg)
        }
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    //页码改变
    change_page(page) {
      this.page = page
      this.search()
    },
    //条数改变
    handleSizeChange(page) {
      this.pageSize = page
      this.page = 1
      this.search()
    },

  }
}
</script>
<style lang="less" scoped>
.container {
  width: 100%;
  height: 100%;
  .filter {
    margin: 20px;
    background-color: #fff;
    box-shadow: 1px 1px 30px rgba(0, 0, 0, 0.1);
    border-radius: 12px;
    padding: 20px;
    position: relative;
    .title {
      font-size: 16px;
    }
    .section {
      display: inline-block;
      vertical-align: middle;
      margin-right: 20px;
      margin-top: 16px;
      .tip {
        font-size: 14px;
        display: inline-block;
        vertical-align: middle;
        margin-right: 5px;
      }
      .content {
        display: inline-block;
        vertical-align: middle;
      }
      .inp {
        display: inline-block;
        vertical-align: middle;
        border: none;
        outline: none;
        border: 1px solid #ccc;
        border-radius: 4px;
        padding: 6px;
      }
    }
    .btn-bar {
      position: absolute;
      right: 60px;
      top: 10px;
    }
  }
  .data-table {
    margin: 20px;
    background-color: #fff;
    box-sizing: border-box;
  }
  .page-controller {
    float: right;
    margin-right: 20px;
  }
}
.block {
  background: #fff;
  padding: 32px 16px;
}
</style>

